package com.dxyxx.framework;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;
import zrc.widget.ZrcListView.OnStartListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.GroupOrder;
import com.dxyxx.pojo.GroupOrderRecords;
import com.dxyxx.pojo.ResponseResult;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.weixinninegridlayout.Image;

public class TicketFragment extends BaseFragment {

	/** 自定义的左右滑动. */
	private ViewPager vp;
	// view pager
	private List<View> list;
	private Context context;
	/**
	 * 初始化
	 */
	private TextView commonText;
	private TextView privateText;
	private View commonTab;
	private View privateTab;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		//setContentView(R.layout.activity_ticket);
		View view = inflater.inflate(R.layout.fragment_ticket, container, false);
		context = getActivity();
		initViews(view);
		setGrid();
		return view;
	}

	private void initViews(View view) {

		list = new ArrayList<View>();

		// 设置tab 变化。
		vp = (ViewPager) view.findViewById(R.id.vp_message_launcher_layout);
		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				setCurPage(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
		commonText = (TextView) view.findViewById(R.id.commonText);
		commonText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (vp.getCurrentItem() != 0) {

					vp.setCurrentItem(0);
					System.out.println(vp.getCurrentItem());
				}
			}
		});
		privateText = (TextView) view.findViewById(R.id.privateText);
		privateText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (vp.getCurrentItem() != 1) {

					vp.setCurrentItem(1);
				}
			}
		});

		commonTab = view.findViewById(R.id.commonTab);
		privateTab = view.findViewById(R.id.privateTab);

	}

	/**
	 * 添加ListView
	 * 
	 */
	private ZrcListView[] listViews;
	private ViewGroup[] waitViewGroups;
	private View[] containers;;
	private OrderMessageAdapter[] messageAdapters;
	private List<Map<String, String>>[] datas;
	private LayoutInflater mInflater;
	private int[] currentPage = { 1, 1 }; // 当前加载页数

	// **设置listview 头部底部的样式
	private void setStyle(ZrcListView listView) {
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(context);
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		listView.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(context);
		footer.setCircleColor(0xff33bbee);
		listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		listView.setItemAnimForTopIn(R.anim.topitem_in);
		listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 开启 加载更多多 的功能
		listView.startLoadMore();
	}

	private void setGrid() {
		// 初始化数据
		listViews = new ZrcListView[2];
		waitViewGroups = new ViewGroup[2];
		containers = new View[2];
		messageAdapters = new OrderMessageAdapter[2];
		datas = new List[2];
		// 在这里添加视图。多个自定义的View
		mInflater = LayoutInflater.from(context);
		for (int i = 0; i < 2; i++) {
			waitViewGroups[i] = (ViewGroup) mInflater.inflate(R.layout.fragment_wait, null);
			containers[i] = mInflater.inflate(R.layout.component_comment_mylistview, null);
			listViews[i] = (ZrcListView) containers[i].findViewById(R.id.zListView);
			listViews[i].setDivider(getResources().getDrawable(R.color.common_list_devider_color));
			listViews[i].setDividerHeight(2);

			setStyle(listViews[i]);
			datas[i] = new ArrayList<Map<String, String>>();
			messageAdapters[i] = new OrderMessageAdapter(context, datas[i]);
		}

		String urlString0 = "order/getTickets?propId=2&currentPage=1&pageSize=" + COUNT;
		HttpUtil.get(urlString0, new DownloadOrderHandler(listViews[0], waitViewGroups[0], messageAdapters[0], 0, false));

		String urlString1 = "order/getTickets?propId=3&currentPage=1&pageSize=" + COUNT;
		HttpUtil.get(urlString1, new DownloadOrderHandler(listViews[1], waitViewGroups[1], messageAdapters[1], 1, false));

		for (int i = 0; i < 2; i++) {
			final int index = i;
			// 下拉刷新事件回调（可选）
			listViews[index].setOnRefreshStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					refresh(index);
				}
			});

			// 加载更多事件回调（可选）
			listViews[index].setOnLoadMoreStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					loadMore(index);
				}
			});

		}

		for (ViewGroup temp : waitViewGroups) {
			list.add(temp);
		}
		vp.setAdapter(new MyAdapter());

	}

	private void refresh(int index) {

		String urlString = "order/getTickets?propId=2&currentPage=1&pageSize=" + COUNT;
		datas[index] = new ArrayList<Map<String, String>>();

		switch (index) {
		case 0:
			urlString = "order/getTickets?propId=2&currentPage=1&pageSize=" + COUNT;
			break;
		case 1:
			urlString = "order/getTickets?propId=3&currentPage=1&pageSize=" + COUNT;
			break;

		default:

			break;
		}
		HttpUtil.get(urlString, new DownloadOrderHandler(listViews[index], waitViewGroups[index], messageAdapters[index], index, true));

	}

	private void loadMore(int index) {
		currentPage[index] = currentPage[index] + 1;

		String urlString = "order/getTickets?propId=2&currentPage=" + currentPage[index] + "&pageSize=" + COUNT;

		switch (index) {
		case 0:
			urlString = "order/getTickets?propId=2&currentPage=" + currentPage[index] + "&pageSize=" + COUNT;
			break;
		case 1:
			urlString = "order/getTickets?propId=3&currentPage=" + currentPage[index] + "&pageSize=" + COUNT;
			break;

		default:

			break;
		}

		HttpUtil.get(urlString, new DownloadMoreOrderHandler(listViews[index], waitViewGroups[index], messageAdapters[index], datas[index], index));

	}

	class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(list.get(arg1));
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(list.get(arg1));
			return list.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

		@Override
		public void finishUpdate(View arg0) {
		}

	}

	/**
	 * 更新当前页码
	 */
	public void setCurPage(int page) {
		switch (page) {
		case 0:
			commonText.setTextColor(0xffFFD101);
			privateText.setTextColor(0xffcccccc);
			// otherText.setTextColor(0xffcccccc);
			commonTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			// otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		case 1:
			privateText.setTextColor(0xffFFD101);
			commonText.setTextColor(0xffcccccc);
			// otherText.setTextColor(0xffcccccc);
			privateTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			// otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;

		default:
			break;
		}
	}

	// 异步下载信息
	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View

	public class OrderMessageAdapter extends BaseAdapter {
		private List<Map<String, String>> data;

		//		private int messageType;

		public OrderMessageAdapter(Context context, List<Map<String, String>> data) {
			this.mInflater = LayoutInflater.from(context);
			this.data = data;
			//			this.messageType = messageType;
		}

		// ViewHolder静态类
		private LayoutInflater mInflater = null;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Map<String, String> map = this.data.get(position);

			holder = null;

			//int type = getItemViewType(position);
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局

				convertView = mInflater.inflate(R.layout.item_ticketlist, null);

				holder.moneyText = (TextView) convertView.findViewById(R.id.orderMoney);
				holder.dateText = (TextView) convertView.findViewById(R.id.orderDate);
				holder.timeText = (TextView) convertView.findViewById(R.id.orderTime);
				holder.uuidText = (TextView) convertView.findViewById(R.id.orderId);
				holder.statusText = (TextView) convertView.findViewById(R.id.orderStatus);
				holder.detailText = (TextView) convertView.findViewById(R.id.orderDetail);
				holder.thumbImage = (ImageView) convertView.findViewById(R.id.orderThumb);
				holder.lookButton = (Button) convertView.findViewById(R.id.button);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			holder.moneyText.setText(map.get(MONEY));
			holder.lookButton.setText("查看条形码\n" + map.get(UUID));
			holder.lookButton.setOnClickListener(new LookClickListner(map.get(UUID)));
			if (holder.statusText != null) {
				holder.statusText.setText(map.get(STATUS));
			}
			return convertView;
		}

		@Override
		public int getCount() {
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	class LookClickListner implements OnClickListener {
		private String string;

		public LookClickListner(String string) {
			this.string = string;
		}

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(getActivity(), CommonBarcodeActivity.class);
			intent.putExtra("code", string);
			startActivity(intent);
		}

	}

	static class ViewHolder {
		public TextView detailText;
		public TextView timeText;
		public TextView moneyText;
		public TextView dateText;
		public TextView uuidText;
		public TextView statusText;
		public ImageView thumbImage;
		public Button lookButton;//查看开团吧券的id
	}

	// / 写一个通用的类。
	class DownloadOrderHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private OrderMessageAdapter messageAdapter;
		// private List<Map<String, String>> data;
		private int index;
		private boolean isRefresh;

		public DownloadOrderHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, OrderMessageAdapter messageAdapter, int index, boolean isRefresh) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			// this.data = data;
			this.index = index;
			this.messageAdapter = messageAdapter;
			this.isRefresh = isRefresh;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			listView.setRefreshSuccess("加载失败");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				System.out.println(new String(responseStr));
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, GroupOrderRecords.class);
				ResponseResult<com.dxyxx.pojo.GroupOrderRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloadData = new ArrayList<Map<String, String>>();
				//设置 data

				downloadData = setOrderData(index, result);

				// 设置data ends

				datas[index].addAll(downloadData);
				if (!isRefresh) {

					listView.setAdapter(messageAdapter);
					// listView.refresh(); // 主动下拉刷新
					waitViewGroup.removeAllViews();
					waitViewGroup.addView(containers[index]);

				} else {
					// 刷新

					messageAdapter.data = datas[index];
					messageAdapter.notifyDataSetChanged();
					listView.setRefreshSuccess("加载成功"); // 通知加载成功
					// 开启 加载更多多 的功能
					//listView.startLoadMore();
				}

			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	// / 写一个通用的类。
	class DownloadMoreOrderHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private OrderMessageAdapter messageAdapter;
		private List<Map<String, String>> data;
		private int index;

		public DownloadMoreOrderHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, OrderMessageAdapter messageAdapter, List<Map<String, String>> data, int index) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			this.data = data;
			this.messageAdapter = messageAdapter;
			this.index = index;

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			AgainPlayer.makeCall((Activity) context, "网络异常");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, GroupOrderRecords.class);
				ResponseResult<GroupOrderRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloaddata = new ArrayList<Map<String, String>>();
				//设置 data

				downloaddata = setOrderData(index, result);

				if (downloaddata.size() == 0) {
					listView.stopLoadMore();
				} else {
					data.addAll(downloaddata);
					messageAdapter.notifyDataSetChanged();
					listView.setLoadMoreSuccess(); // 通知加载成功
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private final static String INDEX = "index";
	private final static String TIME = "time";
	private final static String IMAGE = "image";
	private final static String UUIDStr = "UUIDStr";
	private final static String UUID = "uuid";
	private final static String DETAIL = "detail";
	private final static String MONEY = "money";
	private final static String STATUS = "status";
	private final static String DATE = "date";
	final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	final SimpleDateFormat dateSdf = new SimpleDateFormat("MM月dd日");

	private List<Map<String, String>> setOrderData(int index, ResponseResult<GroupOrderRecords> result) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (GroupOrder order : result.getObject().getRecordList()) {
			Map<String, String> map = new HashMap<String, String>();
			map.put(INDEX, index + "");
			map.put(TIME, sdf.format(order.getPostTime()));
			map.put(DATE, dateSdf.format(order.getPostTime()));
			map.put(UUIDStr, "订单编号：" + order.getUuid());
			map.put(UUID, order.getUuid());
			map.put(MONEY, "￥" + order.getMoney());
			map.put("id", order.getId() + "");
			if (order.getOrderProp().getId() == 1) {
				map.put(STATUS, "未支付");
			} else if (order.getOrderProp().getId() == 2) {
				map.put(STATUS, "已支付");
			} else if (order.getOrderProp().getId() == 3) {
				map.put(STATUS, "已消费");
			}
			list.add(map);
		}
		return list;

	}

}